package control;
 
import model.Share;
import model.Time;
import model.Account; 
import java.text.NumberFormat; 
import java.util.Locale;
import java.util.Vector;
import javax.swing.JOptionPane;
import view.AbstractAccountView;
 

/**
 * AccountController.java
 * @author Diego Schmaedech
 * @version 1.0
 * @since Release Beta
 * @link http://code.google.com/p/economylabs
 * Created on August 2, 2008, 2:34 AM
 */
public class AccountController extends AbstractAccountView {
 
    private Account account;
    private Share share;
    private Time time;
     
    private int idSelectedShare;    
    private Vector comboShares = new Vector(6);
    private NumberFormat moneyFormat = NumberFormat.getCurrencyInstance( Locale.US );
    
    /** Creates new form AccountController */
    public AccountController( Account controlledAccount, Share controlledShare, Time controlledTime ) {
        super(controlledAccount);
        setAccount(controlledAccount);
        setShare(controlledShare);
        setTime(controlledTime);
        
        initComponents();
        loadAvaliableShares();
        updateDisplay();
         
        
    }
    
    private void loadAvaliableShares(){
        for( int i = 0; i < 6; i++ ){
            setComboShares( i, getShare().getShareName(i).toString() );
        }
        jcbShares.setModel(new javax.swing.DefaultComboBoxModel( getComboShares()));
            
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jlShare = new javax.swing.JLabel();
        jlAmount = new javax.swing.JLabel();
        jtfAmountOfShare = new javax.swing.JTextField();
        jbBuyShare = new javax.swing.JButton();
        jbSellShare = new javax.swing.JButton();
        jcbShares = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jtfPurchasePrice = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        setBackground(new java.awt.Color(254, 254, 254));
        setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Economista", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("DejaVu Sans", 1, 13), new java.awt.Color(113, 196, 243))); // NOI18N
        setPreferredSize(new java.awt.Dimension(500, 150));

        jlShare.setFont(new java.awt.Font("DejaVu Sans", 1, 13));
        jlShare.setText("Escolha o Ativo:");

        jlAmount.setFont(new java.awt.Font("DejaVu Sans", 1, 13));
        jlAmount.setText("Quantidade:");

        jtfAmountOfShare.setColumns(7);
        jtfAmountOfShare.setText("1");
        jtfAmountOfShare.setToolTipText("<html>Escolha a quantidade de ativos para <b>comprar</b> ou <b>vender</b>.</html>");

        jbBuyShare.setBackground(new java.awt.Color(254, 254, 254));
        jbBuyShare.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
        jbBuyShare.setText("Comprar");
        jbBuyShare.setToolTipText("<html>Acione para <b>comprar</b> a quantidade de ativos escolhidos</html>");
        jbBuyShare.setPreferredSize(new java.awt.Dimension(150, 40));
        jbBuyShare.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buySelectedShare(evt);
            }
        });

        jbSellShare.setBackground(new java.awt.Color(254, 254, 254));
        jbSellShare.setFont(new java.awt.Font("DejaVu Sans", 1, 13));
        jbSellShare.setText("Vender");
        jbSellShare.setToolTipText("<html>Acione para <b>vender </b>a quantidade de ativos escolhidos. </html>");
        jbSellShare.setPreferredSize(new java.awt.Dimension(150, 40));
        jbSellShare.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sellSelectedShare(evt);
            }
        });

        jcbShares.setBackground(new java.awt.Color(254, 254, 254));
        jcbShares.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "", "", "", "", "", "" }));
        jcbShares.setToolTipText("<html> Selecione aqui o ativo para <b>comprar</b> ou <b>vender</b>.</html>");
        jcbShares.setAutoscrolls(true);
        jcbShares.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jcbShares.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jcbShareItemChange(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("DejaVu Sans", 1, 13));
        jLabel1.setText("<html>       Pre&ccedil;o:</html>");

        jtfPurchasePrice.setColumns(10);
        jtfPurchasePrice.setEditable(false);

        jButton1.setBackground(new java.awt.Color(254, 254, 254));
        jButton1.setForeground(new java.awt.Color(113, 196, 243));
        jButton1.setText("Salvar Dados...");
        jButton1.setToolTipText("<html> Os dados serão salvos no formato <b>tabela:</b> \n<br/>\n<table>\n<tr><th>Index <th> Share <th> Action <th> Amount <th> Price <th> Return <th> Balance <th> Period <th> Opening Money </th>\n<tr><td> 0      <td> 0         <td> 0         <td> 0            <td> 0       <td> 0         <td> 0            <td> 0         <td> 0                       <td>\n</tr>\n</table>\n<br/>\n</html>");
        jButton1.setPreferredSize(new java.awt.Dimension(100, 30));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveAs(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jlAmount)
                    .addComponent(jlShare, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jcbShares, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jtfAmountOfShare))
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jtfPurchasePrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jbBuyShare, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbSellShare, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlShare)
                    .addComponent(jcbShares, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jtfPurchasePrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtfAmountOfShare, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jlAmount))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jbBuyShare, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jbSellShare, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(13, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    @SuppressWarnings("unchecked")
private void buySelectedShare(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buySelectedShare
    
    if( getAccount().isPaused() == false ){ 
        
        Vector vShare = new Vector(1);        
        vShare.add( getShare().getShareName( getIdSelectedShare() ) );//0
        vShare.add( Integer.parseInt( jtfAmountOfShare.getText() ) );//1
        vShare.add( getShare().getPurchasePrice( getIdSelectedShare() ) );//2
        vShare.add( getShare().getPosPurchasePrice( getIdSelectedShare() ) );//3        
        vShare.add( getShare().getVariation( getIdSelectedShare() ) );//4
        vShare.add( getShare().getPosVariation( getIdSelectedShare() ) );//5
        vShare.add( getShare().getCurrentPeriod() );//6
        vShare.add( getAccount().getOpeningMoney() );//7
                
        //efetiva a compra 
        getAccount().buyShare( vShare );
         
    }else{
        JOptionPane.showMessageDialog(this, "<html>Jocker message: <br />Acione <i>Começar</i> para começar a simulação" +
                "<br />" + "ou <i>Salvar Dados</i> para coletar o relatório gerado após o término dos periodos." +
                "<br />" + "Agradecemos sua colaboração!<b>Obrigado ;)</b>" +
                "<br />" +
                "</html>");
    }
    
    
}//GEN-LAST:event_buySelectedShare

private void sellSelectedShare(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sellSelectedShare
    if(getAccount().isPaused() == false){ 
         
        Vector vShare = new Vector(1);
        vShare.add( getShare().getShareName( getIdSelectedShare() ) );//0
        vShare.add( Integer.parseInt( jtfAmountOfShare.getText() ) );//1
        vShare.add( getShare().getPurchasePrice( getIdSelectedShare() ) );//2
        vShare.add( getShare().getPosPurchasePrice( getIdSelectedShare() ) );//3        
        vShare.add( getShare().getVariation( getIdSelectedShare() ) );//4
        vShare.add( getShare().getPosVariation( getIdSelectedShare() ) );//5
        vShare.add( getShare().getCurrentPeriod() );//6
        vShare.add( getAccount().getOpeningMoney() );//7
         
        getAccount().sellShare( vShare ); 
        
    }else{
        JOptionPane.showMessageDialog(this, "<html>Jocker message: <br />Acione <i>play</i> para começar a simulação" +
                "<br/>" + "ou <i>Salvar Dados</i> para coletar o relatório gerado após o término dos periodos." +
                "<br/>" + "Agradecemos sua colaboração!<b>Obrigado ;)</b>" +
                "<br/>" +
                "</html>");
    }
}//GEN-LAST:event_sellSelectedShare

private void jcbShareItemChange(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jcbShareItemChange
    setIdSelectedShare(jcbShares.getSelectedIndex());
    jtfPurchasePrice.setText( moneyFormat.format( getShare().getPurchasePrice( getIdSelectedShare() ) ) );     
}//GEN-LAST:event_jcbShareItemChange

private void saveAs(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveAs
    getAccount().saveAs();
}//GEN-LAST:event_saveAs


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JButton jbBuyShare;
    private javax.swing.JButton jbSellShare;
    private javax.swing.JComboBox jcbShares;
    private javax.swing.JLabel jlAmount;
    private javax.swing.JLabel jlShare;
    private javax.swing.JTextField jtfAmountOfShare;
    private javax.swing.JTextField jtfPurchasePrice;
    // End of variables declaration//GEN-END:variables

    @Override
    public Account getAccount() {
        return account;
    }

    public void setAccount(Account account) {
        this.account = account;
    }
    
    public Share getShare() {
        return share;
    }
    
    public void setShare(Share share) {
        this.share = share;
    }
  
    public Time getTime() {
        return time;
    }
    
    private void setTime(Time time) {
        this.time = time;
    }
     
    public int getIdSelectedShare() {
        return idSelectedShare;
    }

    public void setIdSelectedShare(int idSelectedShare) {
        this.idSelectedShare = idSelectedShare;
    }

    public Vector getComboShares() {
        return comboShares;
    }

    public void setComboShares(int index, String avaliableShare) {
        this.comboShares.add(index, avaliableShare);
    }

    @Override
    public void updateDisplay() {
      jtfPurchasePrice.setText( moneyFormat.format( getShare().getPurchasePrice( getIdSelectedShare() ) ));
  }
}
